

package com.yeyks.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.account.param.AccountInfoQueryParam;
import com.yeyks.account.service.SysUserRoleService;
import com.yeyks.annotation.Login;
import com.yeyks.annotation.LoginUser;
import com.yeyks.annotation.NeedToken;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.base.PageInfo;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.utils.Result;
import com.yeyks.common.validator.Assert;
import com.yeyks.common.validator.ValidatorUtils;
import com.yeyks.common.validator.group.AddGroup;
import com.yeyks.common.validator.group.UpdateGroup;
import com.yeyks.commonReference.pojo.dto.AddSysUserDTO;
import com.yeyks.commonReference.pojo.dto.UpdateSysUserDTO;
import com.yeyks.commonReference.service.account.AccountInfoService;
import com.yeyks.web.AccountUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 系统用户
 *
 * @author administrator
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
//	@Autowired
//	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	AccountInfoService accountService;
	
	/**
	 * 初始化账号权限
	 */
	@Login
	@ApiOperation(value = "账号角色初始化", notes = "roleIds，逗号分隔角色id")
	@RequestMapping(value = "/initRole", method = RequestMethod.POST)
	@RequiresPermissions("sys:user:list")
	public Result initRole(@RequestParam(name = "userType",required = true) Integer userType,
						   @RequestParam(name = "deptId",required = true) Integer deptId,
						   @RequestParam(name = "roleIds",required = true) String roleIds,
						   @RequestParam(name = "token",required = true) String token){

		String[] roleIdArray = roleIds.split(",");
		List<Long> roleIdList = new ArrayList<>();
		if(userType==null||roleIdArray.length<1)
		{
			throw new ServiceException("参数错误");
		}else{
			for(String id:roleIdArray)
			{
				roleIdList.add(Long.valueOf(id));
			}
		}
		List<AccountInfo> list = accountService.queryNoRoleUser(userType) ;
		for(AccountInfo user:list)
		{
			//初始化部门
			user.setDeptId(deptId);
			accountService.update(user);
			//初始化角色
			sysUserRoleService.saveOrUpdate(Long.valueOf(user.getId()), roleIdList);
		}

		return Result.ok("成功初始化用户："+list.size()+"个");
	}

	@NeedToken
	@ApiOperation(value = "分页查询子账号", notes = "根据参数子账号")
	@PostMapping(value = {"/list/subUser"})
	public ResponseEntity<AjaxResponseBody> querySubUserList(@Validated AccountInfoQueryParam accountInfoQueryParam,
															 @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
															 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
															 @RequestParam(name = "token",required = true) String token,
															 HttpServletRequest request
	){
		if(accountInfoQueryParam==null)
		{
			throw new ServiceException("查询参数为空");
		}
        AccountInfo loginUser = AccountUtils.getLoginUser();
		PageInfo pageInfo = PageInfo.of(pageNum, pageSize);
		accountInfoQueryParam.setManagerId(Long.valueOf(loginUser.getId()));
		accountInfoQueryParam.setType(loginUser.getType());
		accountInfoQueryParam.setOffset(pageInfo.getOffset());
		accountInfoQueryParam.setLimit(pageInfo.getLimit());

		Map<String, Object> map = new HashMap<String, Object>();
		//分页查询部门下子账号
		List<AccountInfo> accountInfos = accountService.querySubUserList(accountInfoQueryParam);
		int count = accountService.querySubUserListCount(accountInfoQueryParam);
		map.put("list",accountInfos);
		map.put("count",count);
		return ResponseEntity.ok(AjaxResponseBody.success(map));
	}



	
	/**
	 * 获取登录的用户信息
	 */
	@Login
	@RequestMapping(value = "/info", method = RequestMethod.POST)
	public Result info(@ApiIgnore @LoginUser AccountInfo user ,@RequestParam(name = "token",required = true) String token){
		return Result.ok().put("user", user);
	}
	

	
	/**
	 * 用户信息
	 */
	@Login
	@RequestMapping(value = "/info/{userId}", method = RequestMethod.POST)
	@RequiresPermissions("sys:user:info")
	public Result info(@ApiIgnore @LoginUser AccountInfo loginUser, @PathVariable("userId") Long userId, @RequestParam(name = "token",required = true) String token){
		AccountInfo user = accountService.getById(userId);
		
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		return Result.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	//@SysLog("保存用户")
	@ApiOperation(value = "添加子账号")
	@Login
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@RequiresPermissions("sys:user:save")
	public Result save(@ApiIgnore @LoginUser AccountInfo loginUser, AddSysUserDTO addUser){
		ValidatorUtils.validateEntity(addUser, AddGroup.class);

		QueryWrapper<AccountInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda()
				.eq(AccountInfo::getUsername, addUser.getUsername()) ;
		List<AccountInfo> list =  accountService.list(queryWrapper);
		if(list!=null&&list.size()>0)
		{
			throw new ServiceException("账号："+addUser.getUsername()+"已经存在");
		}
		loginUser.setUsername(addUser.getUsername());
		loginUser.setName(addUser.getName());
		loginUser.setPhone(addUser.getPhone());
		loginUser.setEmail(addUser.getEmail());
		loginUser.setPassword(addUser.getPassword());
		loginUser.setRoleIdList(addUser.getRoleIdList());
		loginUser.setManagerId(loginUser.getId());
		loginUser.setParentId(null);
		accountService.saveUser(loginUser);
		
		return Result.ok();
	}


	/**
	 * 修改用户
	 */
	//@SysLog("修改用户")
	@ApiOperation(value = "编辑", notes = "编辑账户")
	@Login
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@RequiresPermissions("sys:user:update")
	public Result update(UpdateSysUserDTO user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		AccountInfo dbuser = accountService.getById(user.getId());
		if(null!=user)
		{
			dbuser.setName(user.getName());
			dbuser.setPhone(user.getPhone());
			dbuser.setEmail(user.getEmail());
			dbuser.setRoleIdList(user.getRoleIdList());
			accountService.update(dbuser);
		}
		return Result.ok();
	}

	@ApiOperation(value = "禁用、启用", notes = "禁用启用账户")
	@Login
	@RequestMapping(value = "/valid", method = RequestMethod.POST)
	@RequiresPermissions("sys:user:update")
	public Result valid(@RequestParam(name = "valid",required = true) Integer valid,@RequestParam(name = "userId",required = true) Long userId){

        Assert.isNull(valid,"状态参数为空");
		Assert.isNull(userId,"userId参数为空");
		accountService.updateValid(userId,1==valid);
		return Result.ok("操作成功");
	}

	@ApiOperation(value = "修改密码", notes = "修改密码")
	@Login
	@RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
	@RequiresPermissions("sys:user:update")
	public Result modifyPassword(@RequestParam(name = "password",required = true) String password,@RequestParam(name = "userId",required = true) Long userId){
		Assert.isNull(userId,"userId参数为空");
		Assert.isNull(password,"password参数为空");
		accountService.updatePassword(userId,"",password);
		return Result.ok("操作成功");
	}
	
	/**
	 * 删除用户
	 */
	//@SysLog("删除用户")
	@Login
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@RequiresPermissions("sys:user:delete")
	public Result delete(@ApiIgnore @LoginUser AccountInfo user ,@RequestBody Long[] userIds,@RequestParam(name = "token",required = true) String token){
		if(ArrayUtils.contains(userIds, 1L)){
			return Result.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, user.getId())){
			return Result.error("当前用户不能删除");
		}

		accountService.removeByIds(Arrays.asList(userIds));
		
		return Result.ok();
	}
}
